package com.fdb.efp.basic.framework.mail.recv;

import javax.mail.Flags;

import com.fdb.efp.basic.framework.mail.common.MailServerType;
import com.fdb.efp.basic.framework.mail.config.MailConfig;

import jodd.mail.EmailFilter;
import jodd.mail.MailServer;
import jodd.mail.ReceiveMailSession;
import jodd.mail.ReceivedEmail;

 /**
  * 默认邮件接收的实现类
  * @author hengyh
  * @since 2019年3月15日 下午3:44:49
  * @version 1.0
  */
public class DefaultMailReceiverImpl implements ConfigurableMailReceiver {

    private MailConfig config;

    public DefaultMailReceiverImpl(MailConfig config) {
        this.config = config.copy();
    }

    @Override
    public ReceivedEmail[] receiveUnreadEmail(boolean mark, boolean delete) {
        return receive(true, mark, delete);
    }

    @Override
    public ReceivedEmail[] receiveAllEmail(boolean mark, boolean delete) {
        return receive(false, mark, delete);
    }

    private ReceivedEmail[] receive(boolean unread, boolean mark, boolean delete) {
        MailServer<ReceiveMailSession> server = createServer(config);
        ReceiveMailSession session = server.createSession();
        try {
            session.open();
            EmailFilter seenFilter = unread ? EmailFilter.filter().flag(Flags.Flag.SEEN, false) : null;
            ReceivedEmail[] emails;
            if (mark && (!delete || config.serverType() == MailServerType.POP3)) {
                emails = session.receiveEmailAndMarkSeen(seenFilter);
            } else if (delete) {
                emails = session.receiveEmailAndDelete(seenFilter);
            } else {
                emails = session.receiveEmail(seenFilter);
            }
            return emails;
        } finally {
            session.close();
        }
    }

    private MailServer<ReceiveMailSession> createServer(MailConfig config) {
        final MailConfig local = this.config;
        MailServer.Builder builder = MailServer.create().
                host(local.serverAddress()).
                port(local.port()).
                ssl(local.ssl()).
                auth(local.username(), local.password());
               
        switch (local.serverType()) {
        case POP3:
            return builder.buildPop3MailServer();
        case IMAP:
            return builder.buildImapMailServer();
        case SMTP:
        default:
            throw new IllegalArgumentException("不支持使用该类型的Server接收Mail，类型：" + local.serverType());
        }
    }

    @Override
    public void setConfig(MailConfig config) {
        this.config = config.copy();
    }
}
